
// pages/items_list/items_list.js
const db = wx.cloud.database()
Page({
  data: {
    items: []
  },
  onPullDownRefresh(){
    this.onLoad();
  },
  
  onLoad: function () {
    const app = getApp(); // 获取小程序实例
    const dormitoryId = app.globalData.dormitoryId; 
    console.log(dormitoryId);
    // 获取数据库中所有物品信息
    db.collection("items_image").where({dormitoryId:dormitoryId}).get().then(res => {
      this.setData({
        items: res.data
      })
    })
  },
  editItem: function(e) {
    const itemId = e.currentTarget.dataset.id;
    const selectedItem = this.data.items.filter(item => item._id === itemId)[0];
    console.log(selectedItem);
    wx.navigateTo({
      url: `/pages/items/items?item=${JSON.stringify(selectedItem)}&id=${selectedItem._id}`,
    });
  },
  onShow: function () {
    const app = getApp(); // 获取小程序实例
    const dormitoryId = app.globalData.dormitoryId; 
    // 获取数据库中所有物品信息
    db.collection("items_image").where({dormitoryId:dormitoryId}).get().then(res => {
      this.setData({
        items: res.data
      })
    })
  },
  addItem: function() {
    wx.navigateTo({
      url: '/pages/items/items'
    });
  },
  deleteItem(e) {
    const itemId = e.currentTarget.dataset.id; // 获取要删除的物品的id
    const selectedItem = this.data.items.filter(item => item._id === itemId)[0];
    db.collection('items_image').doc(selectedItem._id).remove();
    this.onShow()
  },
})
